package cn.tedu.tmall.front.mall.dao.repository.impl;

import cn.tedu.tamll.common.consts.PassportCacheConsts;
import cn.tedu.tamll.common.pojo.po.PermissionPO;
import cn.tedu.tamll.common.pojo.po.UserCachePO;

import cn.tedu.tmall.front.mall.dao.repository.IUserCacheRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class UserCacheRepository implements IUserCacheRepository, PassportCacheConsts {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 取出存入redis中的数据
     * @param userId
     * @return
     */

    @Override
    public UserCachePO getUserState(Long userId) {
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        String key =KEY_PREFIX_USER_STATE + userId;
        Integer enable = (Integer)hashOperations.get(key, "enable");
        List<PermissionPO> auth =  (List<PermissionPO>)hashOperations.get(key, "auth");
        UserCachePO userCachePO = new UserCachePO();
        userCachePO.setEnable(enable);
        userCachePO.setPermissions(auth);
        userCachePO.setUserId(userId);
        return userCachePO;
    }

    @Override
    public void deleteUserCache(Long userId) {
        String key = KEY_PREFIX_USER_STATE + userId;
        redisTemplate.delete(key);
    }

    @Override
    public void renewal(Long userId) {
        String key = KEY_PREFIX_USER_STATE + userId;
        redisTemplate.expire(key,10L, TimeUnit.MINUTES);
    }
}
